package com.ihd.ihardwaretools.view.view;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.JsonObject;
import com.ihd.ihardwaretools.R;
import com.ihd.ihardwaretools.databinding.ActivityLoginBinding;
import com.ihd.ihardwaretools.pojo.LoginRes;
import com.ihd.ihardwaretools.view.viewmodel.LoginViewModel;

import cn.wowjoy.commonlibrary.app.Constans;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;

public class LoginActivity extends BaseActivity<ActivityLoginBinding, LoginViewModel> {

    @Override
    protected void init(Bundle savedInstanceState) {
        if (!TextUtils.isEmpty(SPUtils.getString(Constans.GATEWAY_TOKEN, ""))) {
            Intent i = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(i);
            finish();
            return;
        }

        mImmersionBar.statusBarDarkFont(false).init();
        binding.mtitlebar.setTitle("登录");
        binding.mtitlebar.setTitleColor(getResources().getColor(R.color.C_FFFFFF));

        binding.loginTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.login(binding.username.getText().toString(), binding.psw.getText().toString());
            }
        });


        setRx(Constans.LOGIN, new BaseConsumer<LoginRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(LoginActivity.this);
            }

            @Override
            protected void onSuccess(LoginRes mLiveData) {
                JsonObject mParam = new JsonObject();
                mParam.addProperty("userId", mLiveData.getData().getId());
                mParam.addProperty("nickname", mLiveData.getData().getNickname());
                SPUtils.putString(Constans.GATEWAY_TOKEN, mParam.toString());

                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(LoginActivity.this, error.getMessage());
                DialogUtils.dismiss(LoginActivity.this);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected Class getViewModelClass() {
        return LoginViewModel.class;
    }
}
